<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>账号管理</title>
    <link rel="stylesheet" href="../../component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../admin/css/other/department.css"/>
</head>
<style>
    .t-click {
        user-select: none;
    }

    .dtree-zdy-item {
        line-height: 50px;
    }

    /* zdy主题风格*/
    .dtree-zdy-item-this {
        background-color: rgba(232, 230, 230, 0.86) !important;
        border-right: 5px solid rgb(54, 179, 104) !important;
    }

    /* 当前选中行样式*/
    .dtree-zdy-item:hover {
        background-color: rgba(242, 242, 242, 0.84) !important;
    }

    /* 行悬停样式*/
    .dtree-zdy-item cite {
        font-size: 14px !important;
    }

    .dtree-zdy-item:hover cite {
        color: #096a3b !important
    }

    /* 行悬停文字样式*/
    .dtree-zdy-dtreefont {
        font-size: 30px !important;
    }

    /* 一级图标、二级图标、复选框样式*/
    .dtree-zdy-ficon {
        color: #2F4056 !important;
    }

    /*一级图标特定样式*/
    .dtree-zdy-icon {
        color: #2F4056 !important;
    }

    /*二级图标特定样式*/
    .dtree-zdy-checkbox:hover {
        color: #11824b !important;
    }

    /*复选框悬停样式*/
    .dtree-zdy-choose {
        color: #11824b !important;
    }


</style>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="username" placeholder="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-row layui-col-space15">
    <div class="layui-col-md3">
        <div class="layui-card">
            <div class="layui-card-body">
                <div id="organizationTreeContent" style="overflow: auto">
                    <ul id="organizationTree" class="dtree organizationTree" data-id="9527"></ul>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-md9">
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="organization-table" lay-filter="organization-table"></table>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="organization-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
        <i class="layui-icon layui-icon-delete"></i>
        删除
    </button>
</script>

<script type="text/html" id="organization-bar">
    <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit"><i
            class="layui-icon layui-icon-edit"></i></button>
    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i
            class="layui-icon layui-icon-delete"></i></button>
</script>
<script src="../../component/layui/layui.js"></script>
<script src="../../component/pear/pear.js"></script>

<script>
    layui.use(['upload', 'table', 'form', 'jquery', 'dtree'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let dtree = layui.dtree;
        let MODULE_PATH = "operate/";


        let cols = [
            [{
                type: 'checkbox'
            },
                {
                    title: '账号',
                    field: 'userName',
                    align: 'center'
                },
                {
                    title: '密码',
                    field: 'md5password',
                    align: 'center'
                },
                {
                    title: '账号权限',
                    templet: function (d) {
                        if (d.role == '0') {
                            return '<span class="layui-badge layui-bg-green">管理员</span>'
                        } else if (d.role == '1') {
                            return '<span class="layui-badge layui-bg-blue">教师账号</span>'
                        } else {
                            return '<span class="layui-badge layui-bg-gray">学生账号</span>'
                        }


                    },
                    field: 'role',
                    align: 'center'

                },
                {
                    title: '账号状态',
                    templet: function (d) {
                        if (d.status == '100') {
                            return '<input class="statusSwitch" type="checkbox" data-role="' + d.role + '" name="status" value="'
                                + d.userName + '"\n' +
                                ' lay-skin="switch" lay-text="启用|禁用" lay-filter="user-status"\n' +
                                ' checked lay-event="changeStatus">'
                        } else if (d.status == '110') {
                            return '<input class="statusSwitch" type="checkbox" data-role="' + d.role + '" name="status" value="'
                                + d.userName + '"\n' +
                                ' lay-skin="switch" lay-text="启用|禁用" lay-filter="user-status"\n' +
                                ' lay-event="changeStatus">'
                        }
                    },
                    field: 'status',
                    align: 'center'

                },
                {
                    title: '操作',
                    toolbar: '#organization-bar',
                    align: 'center',
                    width: 130
                }
            ]
        ]

        let DTree = dtree.render({
            elem: "#organizationTree",
            iconfont: ["layui-icon", "dtreefont", "iconfont"],
            iconfontStyle: [{
                fnode: {  //一级节点
                    node: {  //非叶子节点
                        open: "layui-icon-subtraction",  //节点展开
                        close: "layui-icon-addition"  //节点关闭
                    },
                    leaf: "layui-icon-username"  //叶子节点
                }, snode: {  //二级节点
                    node: {  //非叶子节点
                        open: "layui-icon-user",  //节点展开
                        close: "layui-icon-user"  //节点关闭
                    },
                    leaf: ""  //叶子节点
                }
            }],
            skin: "zdy",
            //data: data,
            initLevel: "2", //默认展开层级为1
            line: false, // 有线树
            // ficon: ["1", "-1"], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
            // icon: ["0", "2"], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
            method: 'get',
            url: "../../admin/data/organizationtree.json",

        });

        let tableIns = table.render({
            elem: '#organization-table',
            url: '/User/getAllUsers',
            title:'智慧校园系统用户表',
            initSort: {
                field: 'role' //排序字段，对应 cols 设定的各字段名
                , type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            },
            height: 'full-150',
            method: "post",
            page: {
                layout: ['count', 'prev', 'page', 'next', 'skip']
                , curr: 1
                , groups: 3
                , limit: 8
                , last: false
            },
            cols: cols,
            skin: 'line',
            toolbar: '#organization-toolbar',
            defaultToolbar: [{
                title: '刷新账号列表',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
            }, 'filter', 'print', 'exports'],
            parseData: function (res) { //将原始数据解析成 table 组件所规定的数据，res为从url中get到的数据
                let result;
                console.log(res);
                // res.data[0].birthday = dateFormat(res.data[0].birthday, 'Y-M-D')
                if (this.page.curr) {
                    result = res.data.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                } else {
                    result = res.data.slice(0, this.limit);
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": result //解析数据列表
                };
            }
        });

        // 绑定节点点击事件
        dtree.on("node(organizationTree)", function (obj) {
            console.log(obj.param.nodeId);
            let role = '';
            if (obj.param.nodeId == '001') {
                role = '0';
                //DTree.clickSpread($div); //调用内置函数展开节点
            } else if (obj.param.nodeId == '002') {
                role = '1';
                //table.reload("organization-table");
            } else if (obj.param.nodeId == '003') {
                role = '2';
            } else {
                role = '';
            }
            tableIns.reload({
                url: '/User/getRoleAccounts',
                method: 'post',
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'skip']
                    , curr: 1
                    , groups: 3
                    , last: false
                }
                , where: {
                    role: role
                }
            })
        });

        form.on('switch(user-status)', function (obj) {
            let status = '';
            let statusSwitch = document.querySelector(".statusSwitch");
            console.log(obj.elem.dataset["role"]);
            if (obj.elem.dataset["role"] == '0') {
                layer.open({
                    title: '提示'
                    , icon: 2
                    , content: '您无权修改该账号状态'
                    , end: function () {
                        obj.elem.checked = !obj.elem.checked;
                        form.render('checkbox');
                    }
                });
                return false;
            }

            if (obj.elem.checked == false) {
                status = '110'
            } else {
                status = '100'
            }
            //layer.tips(this.value + ' ' + this.name + '：' + status, obj.othis);
            let index = layer.load(2, {
                shade: [0.2, '#323232'] //0.1透明度的白色背景
            });
            $.ajax({
                type: "post",
                url: "/User/updateStatus",
                data: {
                    username: obj.elem.value,
                    status: status,
                    role: obj.elem.dataset["role"]
                },
                dataType: 'json',
                success: function (result) {
                    layer.close(index);
                    if (result.success != '1') {
                        layer.open({
                            title: '提示'
                            , icon: 2
                            , content: result.msg
                            , end: function () {
                                obj.elem.checked = !obj.elem.checked;
                                form.render('checkbox');
                            }
                        });
                    } else {
                        layer.msg('账号状态修改成功', {icon: 1})
                    }
                },
                error: function (res) {
                    layer.close(index);
                    layer.open({
                        title: '服务器处理异常'
                        , icon: 2
                        , content: '修改账号状态失败'
                        , end: function () {
                            obj.elem.checked = !obj.elem.checked;
                            form.render('checkbox');
                        }
                    });
                }
            })
        });


        table.on('tool(organization-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            }
        });

        table.on('toolbar(organization-table)', function (obj) {
            console.log(obj.event);
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'refresh') {
                window.refresh();
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            }
        });

        form.on('submit(user-query)', function (data) {
            table.reload('organization-table', {
                url: '/User/searchAccount',
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'skip']
                    , curr: parent.layui.jquery(".layui-laypage-em").next().html()
                    , groups: 3
                    , last: false
                },
                where: data.field
            })
            return false;
        });


        window.add = function () {
            layer.open({
                type: 2,
                title: '新增账号',
                shade: 0.1,
                area: ['500px', '500px'],
                content: MODULE_PATH + 'addAccount.html'
            });
        }

        window.edit = function (obj) {
            let newTitle = '修改：' + obj.data['userName']
            if (obj.data['role'] === '0') {
                newTitle = '修改：' + obj.data['userName'] + '（管理员）'
            }
            layer.open({
                type: 2,
                title: newTitle,
                shade: 0.1,
                area: ['500px', '400px'],
                content: MODULE_PATH + 'editAccount.html',
                success: function (layero, index) {
                    let body = layer.getChildFrame('body', index);
                    //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    console.log(obj.data);
                    let iframeWin = window[layero.find('iframe')[0]['name']]
                    body.find('#username').val(obj.data['userName'])
                    //body.find('#password').val(obj.data['md5password'])
                    if (obj.data['role'] === '0') {
                        body.find('#role1').attr("selected", "");
                        body.find('#role2').attr("disabled", "");
                        body.find('#role3').attr("disabled", "");
                        iframeWin.layui.form.render('select');
                    } else if (obj.data['role'] === '1') {
                        body.find('#role2').attr("selected", "");
                        iframeWin.layui.form.render('select');
                    } else if (obj.data['role'] === '2') {
                        body.find('#role3').attr("selected", "");
                        iframeWin.layui.form.render('select');
                    }
                }
            });
        }

        window.remove = function (obj) {
            console.log(obj.data.userName);
            layer.confirm('确定要删除该用户', {
                icon: 3,
                title: '提示'
            }, function (ind) {
                layer.close(ind);
                let index = layer.load(2, {time: 10 * 1000});
                $.ajax({
                    url: '/User/removeAccount',
                    data: {
                        username: obj.data.userName
                    },
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(index);
                        if (result.success === '1') {
                            layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                                tableIns.reload({
                                    url: '/User/getAllUsers',
                                    page: {
                                        layout: ['count', 'prev', 'page', 'next', 'skip']
                                        , curr: $(".layui-laypage-em").next().html()
                                        , groups: 3
                                        , last: false
                                    }
                                });
                            });
                        } else {
                            layer.open({
                                title: '提示'
                                , icon: 2
                                , content: result.msg
                            });
                        }
                    },
                    error: function () {
                        layer.close(index);
                        layer.open({
                            title: '服务器处理异常'
                            , icon: 2
                            , content: '删除账号失败'
                        });
                    }
                })
            });
        }

        window.batchRemove = function (obj) {

            let data = table.checkStatus(obj.config.id).data;
            console.log(data);
            for (let i = 0; i < data.length; i++) {
                if (data[i].role === '0') {
                    layer.open({
                        title: '权限不足'
                        , icon: 0
                        , content: '所选账号中包含管理员账号，请将其移出后再尝试'
                    })
                    return false;
                }
            }
            if (data.length === 0) {
                layer.msg("未选中数据", {
                    icon: 3,
                    time: 1000
                });
                return false;
            }

            layer.confirm('确定要删除这些用户', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let checkStatus = table.checkStatus('organization-table');
                let userNames = [];
                for (let i = 0; i < checkStatus.data.length; i++) {
                    userNames[i] = checkStatus.data[i].userName;
                    //console.log(checkStatus.data[i].userId);
                }
                // console.log(userNames);
                // return false;
                let loading = layer.load(2, {
                    shade: [0.2, '#323232'] //0.1透明度的白色背景
                });
                $.ajax({
                    url: "/User/batchRemoveAccount",
                    data: {
                        userNames: JSON.stringify(userNames)
                    },
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.success) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                tableIns.reload({
                                    url: "/User/getAllUsers",
                                    page: {
                                        layout: ['count', 'prev', 'page', 'next', 'skip']
                                        , curr: 1
                                        , groups: 3
                                        , last: false
                                    },
                                    method: "post"
                                });
                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }
                })
            });
        }

        window.refresh = function (param) {
            table.reload('organization-table');
        }
    })
</script>
</body>
</html>
